package com.snail.auth.service;

import com.common.util.StringUtil;
import com.snail.auth.dao.AuthOrgRep;
import com.snail.auth.entity.AuthOrg;
import com.snail.auth.entity.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.*;

@Service
@Transactional
public class AuthOrgService {
    @Autowired
    private AuthOrgRep orgRep;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private AuthUserService userService;


    /**
     * 根据部门职能查询部门信息
     */
    public List<AuthOrg> findByFunctionType(Integer functionType) {
        return orgRep.findByFunctionType(functionType);
    }

    public AuthOrg save(AuthOrg entity) {
        if (entity.getFlag() == null) {
            entity.setFlag(0);
        }
        orgRep.save(entity);
        return entity;
    }

    public void del(Long id) {
        AuthOrg dept = orgRep.getOne(id);
        dept.setFlag(1);
        orgRep.saveAndFlush(dept);
        orgRep.deleteById(id);
    }

    public List<AuthOrg> list(Map<String, Object> params) {
        StringBuilder hql = new StringBuilder("from AuthOrg where flag=0");
        if (!StringUtil.isEmpty(params.get("functionType"))) {
            hql.append(" and functionType = " + params.get("functionType"));
        }
        hql.append(" order by sort");
        return entityManager.createQuery(hql.toString()).getResultList();
    }

    public AuthOrg getByKey(Long id) {
        Optional optional = orgRep.findById(id);
        if (optional.isPresent()) {
            return (AuthOrg) optional.get();
        }
        return null;
    }

    public boolean exist(Long id) {
        AuthOrg org = getByKey(id);
        if(org==null){
            return false;
        }
        return true;
    }

    public Long newId(Long parentId, Integer functionType) {
        if (parentId == null) {
            List<AuthOrg> list = orgRep.execHql("from AuthOrg where parentId=0 order by id desc");
            if (list.size() > 0) {
                return list.get(0).getId() + 1;
            }
            return 10L;
        } else {
            List<AuthOrg> list = orgRep.execHql("from AuthOrg where parentId=" + parentId + " order by id desc");
            if (list.size() > 0) {
                return list.get(0).getId() + 1;
            } else {
                if (functionType != null && functionType == 9) {//门店
                    return parentId * 10000 + 1;
                } else {
                    return parentId * 100 + 1;
                }
            }
        }
    }

    /**
     * 获取符合element使用的多级结构树
     */
    public List<Map<String, Object>> treeData() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<AuthOrg> datas = orgRep.execHql("from AuthOrg where flag=0 order by sort");
        Map<Long, List<AuthOrg>> midMap = new HashMap<>();
        for (AuthOrg data : datas) {
            if (!midMap.containsKey(data.getParentId())) {
                midMap.put(data.getParentId(), new ArrayList<>());
            }
            midMap.get(data.getParentId()).add(data);
        }
        return pushTreeData(result, midMap, 0L);
    }

    private List<Map<String, Object>> pushTreeData(List<Map<String, Object>> result, Map<Long, List<AuthOrg>> midMap, Long parentId) {
        for (AuthOrg firOrg : midMap.get(parentId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", firOrg.getId());
            map.put("name", firOrg.getName());
            map.put("parentId", firOrg.getParentId());
            map.put("readonly", firOrg.getReadonly());
            if (midMap.containsKey(firOrg.getId())) {
                List<Map<String, Object>> childs = new ArrayList<>();
                for (AuthOrg secOrg : midMap.get(firOrg.getId())) {
                    Map<String, Object> child = new HashMap<>();
                    child.put("id", secOrg.getId());
                    child.put("name", secOrg.getName());
                    child.put("parentId", secOrg.getParentId());
                    child.put("parentName", firOrg.getName());
                    child.put("readonly", secOrg.getReadonly());
                    if (midMap.containsKey(secOrg.getId())) {
                        child.put("children", pushTreeData(new ArrayList<Map<String, Object>>(), midMap, secOrg.getId()));
                    }
                    childs.add(child);
                }
                map.put("children", childs);
            }
            result.add(map);
        }
        return result;
    }

    /**
     * 查找指定用户的上级经营区域公司
     * @param userId
     * @return
     */
    public AuthOrg getSuperiorManageOrg(Long userId){
        AuthUser user = userService.getByKey(userId);
        AuthOrg org = user.getOrg();
        while (!(org==null || (org.getFunctionType()!=null && org.getFunctionType()==5))){
            org = getByKey(org.getParentId());
        }
        return org;
    }
}
